/**
 * May 19, 2014 5:22:04 PM
 */
package elitech.vietnam.copyweatherfashion.fragments.settings;

import java.io.File;
import java.io.IOException;

import org.xmlpull.v1.XmlPullParserException;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.webkit.URLUtil;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.koushikdutta.urlimageviewhelper.UrlImageViewHelper;

import elitech.vietnam.copyweatherfashion.MainActivity;
import elitech.vietnam.copyweatherfashion.R;
import elitech.vietnam.copyweatherfashion.config.Const;
import elitech.vietnam.copyweatherfashion.dialog.GetImageDialogFragment;
import elitech.vietnam.copyweatherfashion.dialog.GetImageDialogFragment.GetImageChoosen;
import elitech.vietnam.copyweatherfashion.dialog.GetImageDialogFragment.ListenerType;
import elitech.vietnam.copyweatherfashion.dialog.ProgressDialogFragment;
import elitech.vietnam.copyweatherfashion.prefs.PrefsDefinition;
import elitech.vietnam.copyweatherfashion.utilities.Utilities;
import elitech.vietnam.copyweatherfashion.wsclient.ImageUploader;
import elitech.vietnam.copyweatherfashion.wsclient.Service;
import eu.janmuller.android.simplecropimage.CropImage;

/**
 * @author Cong
 */
public class EditProfileFragment extends Fragment implements View.OnClickListener, GetImageChoosen {

	private static final int	MAXCHAR_NAME	= 30;
	private static final int	MAXCHAR_STATUS	= 60;

	MainActivity				mActivity;

	ImageView					mImgAvatar;
	Button						mBtnSave, mBtnEdit;
	TextView					mTxtNameCnt, mTxtStatusCnt;
	EditText					mEdtName, mEdtStatus;

	String						mImagePath;

	public EditProfileFragment() {
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mActivity = (MainActivity) getActivity();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.settings_editprofile, container, false);

		mImgAvatar = (ImageView) view.findViewById(R.id.editprf_imgAvatar);
		mBtnEdit = (Button) view.findViewById(R.id.editprf_btnEditAvatar);
		mBtnSave = (Button) view.findViewById(R.id.editprf_btnSave);
		mTxtNameCnt = (TextView) view.findViewById(R.id.editprf_txtCountName);
		mTxtStatusCnt = (TextView) view.findViewById(R.id.editprf_txtCountProfile);
		mEdtName = (EditText) view.findViewById(R.id.editprf_edtName);
		mEdtStatus = (EditText) view.findViewById(R.id.editprf_edtProfile);

		mBtnEdit.setOnClickListener(this);
		mBtnSave.setOnClickListener(this);

		mEdtStatus.setOnKeyListener(new View.OnKeyListener() {
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_ENTER) {
					int lines = mEdtStatus.getText().toString().length()
							- mEdtStatus.getText().toString().replace("\n", "").length();
					if (lines < 2) {
						return false;
					} else {
						return true;
					}
				}
				return false;
			}
		});

		mEdtName.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				mTxtNameCnt.setText(mEdtName.getText().length() + "/" + MAXCHAR_NAME);
			}
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			}
			@Override
			public void afterTextChanged(Editable s) {
			}
		});

		mEdtStatus.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				mTxtStatusCnt.setText(mEdtStatus.getText().length() + "/" + MAXCHAR_STATUS);
			}
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			}
			@Override
			public void afterTextChanged(Editable s) {
			}
		});

		return view;
	}

	@Override
	public void onStart() {
		super.onStart();
		mActivity.mBtnSaveProfile.setVisibility(View.VISIBLE);
		mActivity.mBtnNotify.setVisibility(View.GONE);
		mActivity.mBtnSaveProfile.setOnClickListener(this);
		mActivity.mBtnSaveProfile.setText(R.string.save);

		mImagePath = (mImagePath == null || mImagePath.length() == 0) ? mActivity.mUser.Image : mImagePath;
		if (mImagePath.equals(mActivity.mUser.Image))
			UrlImageViewHelper.setUrlDrawable(mImgAvatar, Const.SERVER_IMAGE_THUMB_URL + mActivity.mUser.Image, R.drawable.avatar);
		else
			mImgAvatar.setImageURI(Uri.parse(mImagePath));
		mEdtName.setText(mActivity.mUser.Name);
		mEdtStatus.setText(mActivity.mUser.Profile);
		
	}

	@Override
	public void onStop() {
		mActivity.mBtnSaveProfile.setVisibility(View.GONE);
		mActivity.mBtnSaveProfile.setOnClickListener(null);
		super.onStop();
	}
	
	@Override
	public void onResume() {
		super.onResume();
		/*
		 * Having result for action take photo from camera
		 */
		if (mActivity.mRequestCode == MainActivity.REQUEST_EDITCAMERA) {
			Log.w(getClass().getSimpleName(), "" + MainActivity.REQUEST_EDITCAMERA);
			Uri uri = Uri.fromFile(new File(mActivity.mConfig.getImageTemp()));
			Intent intent = new Intent(mActivity, CropImage.class);
			intent.putExtra(CropImage.IMAGE_PATH, uri.getPath());
			intent.putExtra(CropImage.SCALE, true);
			intent.putExtra(CropImage.ASPECT_X, 1);
			intent.putExtra(CropImage.ASPECT_Y, 1);
			mActivity.startActivityForResult(intent, MainActivity.REQUEST_EDITCROP);

			mActivity.mRequestCode = -1;
			mActivity.mResultIntent = null;
		}
		/*
		 * Having result for action take photo from library
		 */
		if (mActivity.mRequestCode == MainActivity.REQUEST_EDITLIBRARY && mActivity.mResultIntent != null) {
			new AsyncTask<Integer, Integer, String>() {
				ProgressDialogFragment mDialog;
				@Override
				protected void onPreExecute() {
					mDialog = new ProgressDialogFragment.Builder().setMessage(getString(R.string.please_wait))
							.setTitle(getString(R.string.loading)).build();
					mDialog.show(getFragmentManager());
				}
				@Override
				protected String doInBackground(Integer... params) {
					/*
					 * Check if the image selected in Google Plus
					 * or on the Internet
					 */
					Uri img = mActivity.mResultIntent.getData();
					String path = "";
					if (img.toString().startsWith("content://com.android.gallery3d.provider"))
						img = Uri.parse(img.toString().replace("com.android.gallery3d", "com.google.android.gallery3d"));
					path = mActivity.getRealPathFromURI(img);
					path = (path == null || path.length() == 0) ? img.toString() : path;
					if (URLUtil.isContentUrl(path) || URLUtil.isHttpsUrl(path) || URLUtil.isHttpUrl(path))
						return Utilities.downloadImage(mActivity, path, mActivity.mConfig.getImageTemp());
					else 
						return mActivity.getRealPathFromURI(img);
				}
				@Override
				protected void onPostExecute(String result) {
					mDialog.dismiss();
					if (result == null) {
						Toast.makeText(mActivity, R.string.invalidimage, Toast.LENGTH_SHORT).show();
						return;
					}
					Uri uri = Uri.fromFile(new File(result));
					Intent intent = new Intent(mActivity, CropImage.class);
					intent.putExtra(CropImage.IMAGE_PATH, uri.getPath());
					intent.putExtra(CropImage.SCALE, true);
					intent.putExtra(CropImage.ASPECT_X, 1);
					intent.putExtra(CropImage.ASPECT_Y, 1);
					mActivity.startActivityForResult(intent, MainActivity.REQUEST_EDITCROP);
					
					mActivity.mRequestCode = -1;
					mActivity.mResultIntent = null;
				};
			}.execute();
		}
		/*
		 * Having result for action crop image
		 */
		if (mActivity.mRequestCode == MainActivity.REQUEST_EDITCROP && mActivity.mResultIntent != null) {
			new AsyncTask<Integer, Integer, Boolean>() {
				String	image	= mActivity.mResultIntent.getStringExtra(CropImage.IMAGE_PATH);
				@Override
				protected Boolean doInBackground(Integer... params) {
					return Utilities.createScaledImage(image, image, Const.MAX_THUMB_WIDTH);
				}
				@Override
				protected void onPostExecute(Boolean result) {
					if (result) {
						mImagePath = image;
						Uri uri = Uri.fromFile(new File(mImagePath));
						mImgAvatar.setImageURI(uri);
					}
					mActivity.mRequestCode = -1;
					mActivity.mResultIntent = null;
				}
			}.execute();
		}
	}
	
	@Override
	public void onDestroy() {
		Log.w(getClass().getSimpleName(), "onDestroy");
		super.onDestroy();
	}

	@Override
	public void onClick(View v) {
		InputMethodManager inputManager = (InputMethodManager) mActivity.getSystemService(Context.INPUT_METHOD_SERVICE);
		View view = mActivity.getCurrentFocus();
	    if (view != null)
	    	inputManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
		switch (v.getId()) {
		case R.id.editprf_btnEditAvatar:
			new GetImageDialogFragment.Builder().setCallback(this, ListenerType.FRAGMENT).build().show(getFragmentManager());
			break;
		case R.id.editprf_btnSave:
			if (mEdtName.getText().length() == 0)
				Toast.makeText(mActivity, R.string.nameempty, Toast.LENGTH_SHORT).show();
			else if (mImagePath.equals(mActivity.mUser.Image)
					&& mEdtName.getText().toString().equals(mActivity.mUser.Name)
					&& mEdtStatus.getText().toString().equals(mActivity.mUser.Profile)) {
				Toast.makeText(mActivity, R.string.infomationhaventchanged, Toast.LENGTH_SHORT).show();
			} else
				new UpdateProfile().execute();
			break;
		case R.id.main_btnSaveProfile:
			if (mEdtName.getText().length() == 0)
				Toast.makeText(mActivity, R.string.nameempty, Toast.LENGTH_SHORT).show();
			else if (mImagePath.equals(mActivity.mUser.Image)
					&& mEdtName.getText().toString().equals(mActivity.mUser.Name)
					&& mEdtStatus.getText().toString().equals(mActivity.mUser.Profile)) {
				Toast.makeText(mActivity, R.string.infomationhaventchanged, Toast.LENGTH_SHORT).show();
			} else
				new UpdateProfile().execute();
			break;
		default:
			break;
		}
	}

	@Override
	public void takeByCamera() {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		intent.putExtra(MediaStore.EXTRA_OUTPUT,
				Uri.fromFile(new File(mActivity.mConfig.getImageTemp())));
		mActivity.startActivityForResult(intent, MainActivity.REQUEST_EDITCAMERA);
	}

	@Override
	public void takeByLibrary() {
		Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
		intent.setType("image/*");
		mActivity.startActivityForResult(intent, MainActivity.REQUEST_EDITLIBRARY);
	}

	class UpdateProfile extends AsyncTask<Integer, Integer, Integer> {
		ProgressDialogFragment	mDialog;
		@Override
		protected void onPreExecute() {
			mDialog = new ProgressDialogFragment.Builder().setMessage(getString(R.string.please_wait))
					.setTitle(getString(R.string.loading)).build();
			mDialog.show(getFragmentManager());
		}
		@Override
		protected Integer doInBackground(Integer... params) {
			String fileName = mActivity.mUser.Id + "_" + System.currentTimeMillis() + ".jpg";
			String filePath = mImagePath;
			String memImage = Const.MEMBER_FOLDER + fileName;
			boolean isUpload = true;
			if (!mImagePath.equals(mActivity.mUser.Image)) {
				isUpload = new ImageUploader().upload(filePath, memImage);
			} else 
				memImage = mImagePath;
			if (!isUpload)
				return -1;
			try {
				int res = new Service().updateUserInfo(mActivity.mUser.Username, mEdtName.getText().toString(),
						mEdtStatus.getText().toString(), memImage, Const.COUNTRYCODE);
				if (res > 0)
					mActivity.mUser.Image = memImage;
				return res;
			} catch (IOException | XmlPullParserException e) {
				e.printStackTrace();
				return -1;
			}
		}
		@Override
		protected void onPostExecute(Integer result) {
			mDialog.dismiss();
			if (result > 0) {
				mActivity.mUser.Name = mEdtName.getText().toString();
				mActivity.mUser.Profile = mEdtStatus.getText().toString();
				if (mActivity.mOptions.mAutoLogin)
					mActivity.mPrefs.edit().putString(PrefsDefinition.USER, new Gson().toJson(mActivity.mUser)).commit();
				Toast.makeText(mActivity, R.string.setting_edit_profile_success, Toast.LENGTH_SHORT).show();
			} else if (result == -2)
				Toast.makeText(mActivity, R.string.nicknameexists, Toast.LENGTH_SHORT).show();
			else
				Toast.makeText(mActivity, R.string.setting_edit_profile_fail, Toast.LENGTH_SHORT).show();
		}
	}
}
